<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.w3.org/1999/xhtml">
<head>
    <th:block th:include="common/common_head :: commonHeader('订单管理')"/>
    <link rel="stylesheet" th:href="@{/static/js/plugins/jquery-layout/jquery.layout-latest.css}">
    <link rel="stylesheet" th:href="@{/static/js/editable/css/bootstrap-editable.css}">
    <!-- <style type="text/css">.table {table-layout:fixed;}</style> -->
</head>
<body class="gray-bg">
<input id="roleName" value="roleName" style="display: none">
<div class="container-div ui-layout-center">
    <div class="row">
        <div class="col-sm-12 search-condition">
            <form id="orderItemForm" th:action="@{/orderItem/list?poFlag=NPRO}" class="form-inline">
                <div class="select-list">
                    <ul>
                        <li class="col-sm-3" style="width: 33%">
                            <label style="width: 120px">采购凭证号：</label>
                            <input type="text" name="poNo" maxlength="10"/>
                        </li>
                        <li class="col-sm-3" style="width: 33%">
                            <label style="width: 120px">订单类型：</label>
                            <select name="poType" sysDict="CGDDLX" emptyFirst="true"></select>
                        </li>
                        <li class="col-sm-3" style="width: 33%">
                            <label style="width: 120px">供应商编码：</label>
                            <input type="text" name="sapCode"/>
                        </li>
                        <li class="col-sm-3" style="width: 33%">
                            <label style="width: 120px">采购组：</label>
                            <select name="purchGroup" sysDict="CGZ" emptyFirst="true"></select>
                        </li>
                        <li class="col-sm-3" style="width: 33%">
                            <label style="width: 120px">总账科目：</label>
                            <input type="text" name="materialCode"/>
                        </li>
                        <li class="col-sm-3" style="width: 33%">
                            <label style="width: 120px">物料描述：</label>
                            <input type="text" name="materialDesc"/>
                        </li>
                        <li class="col-sm-3" style="width: 33.3%">
                            <label style="width: 120px">发货状态：</label>
                            <select id="deliverStatus" name="deliverStatus" emptyFirst="true">
                                <option value=""></option>
                                <option value="0">草稿</option>
                                <option value="-1">已驳回</option>
                                <option value="1">已确认</option>
                                <option value="2">分批发货</option>
                                <option value="3">发货完成</option>
                                <option value="4">已同步SAP</option>
                            </select>
                        </li>
                        <li class="col-sm-3" style="width: 33%" id="factory">
                            <label style="width: 120px">工厂：</label>
                            <select sysDict="GC" emptyFirst="true" name="factory"></select>
                        </li>
                        <li class="col-sm-3" style="width: 33%">
                            <button id="orderItemSearchBtn" type="button" class="btn btn-primary btn-rounded btn-sm"><i
                                    class="fa fa-search"></i>&nbsp;搜索
                            </button>
                            <button class="btn btn-warning btn-rounded btn-sm" type="reset"><i class="fa fa-eraser"></i>&nbsp;重置
                            </button>
                            <button id="orderItemAdvancedSearch" type="button"
                                    class="btn btn-primary btn-rounded btn-sm" style="display: none"><i
                                    class="fa fa-caret-down"></i>&nbsp;高级搜索
                            </button>
                        </li>
                    </ul>
                </div>
            </form>
        </div>

        <div class="col-sm-12 select-info order-table">
            <div class="btn-group hidden-xs toolbar" id="orderItemToolBar" role="group">
                <a class="btn btn-outline btn-danger btn-rounded" onclick="toDelete()"
                   shiro:hasPermission="orderItem:delete">
                    <i class="fa fa-trash-o"></i> 删除
                </a>
                <a class="btn btn-outline btn-success btn-rounded" onclick="toEdit()"
                   shiro:hasPermission="orderItem:changer">
                    <i class="fa fa-edit"></i> 变更
                </a>
                <a class="btn btn-outline btn-success btn-rounded" onclick="toUpdate()"
                   shiro:hasPermission="orderItem:confirm">
                    <i class="fa fa-star"></i> 确认
                </a>
                <a class="btn btn-outline btn-success btn-rounded" onclick="toRemove()"
                   shiro:hasPermission="orderItem:cancel">
                    <i class="fa fa-star"></i> 驳回
                </a>
                <a class="btn btn-outline btn-success btn-rounded" onclick="addReplyDate()"
                   shiro:hasPermission="orderItem:replyDate">
                    <i class="fa fa-star"></i> 回复交期
                </a>
                <a class="btn btn-outline btn-success btn-rounded" onclick="toSendSap()"
                   shiro:hasPermission="orderItem:sendSap">
                    <i class="fa fa-star"></i> 同步SAP
                </a>
                <a class="btn btn-outline btn-success btn-rounded" onclick="toSend()"
                   shiro:hasPermission="orderItem:fahuo">
                    <i class="fa fa-star"></i> 发货
                </a>
                <a class="btn btn-outline btn-success btn-rounded" onclick="toSendBatch()"
                   shiro:hasPermission="orderItem:fpfahuo">
                    <i class="fa fa-plus"></i> 分批发货
                </a>
                <a class="btn btn-outline btn-success btn-rounded" onclick="createDeliverOrder()"
                   shiro:hasPermission="orderItem:deliverOrder">
                    <i class="fa fa-star"></i> 生成送货单
                </a>
                <a class="btn btn-outline btn-success btn-rounded" onclick="showUploadDialog()"
                   shiro:hasPermission="orderItem:uploadFile">
                    <i class="fa fa-upload"></i> 上传文件
                </a>
                <a class="btn btn-outline btn-success btn-rounded" onclick="showdownloadDialog()"
                   shiro:hasPermission="orderItem:downloadFile">
                    <i class="fa fa-download"></i> 下载文件
                </a>
                <a class="btn btn-outline btn-success btn-rounded" onclick="free()"
                   shiro:hasPermission="orderItem:free">
                    <i class="fa fa-star"></i> 免费
                </a>
                <!--暂时注释发送邮件功能，采购若需要，须提供邮箱账号再开启-->
                <!--<a class="btn btn-outline btn-success btn-rounded" onclick="showMailDialog()"
                   shiro:hasPermission="orderItem:sendmail">
                    <i class="fa fa-envelope"></i> 发送邮件
                </a>-->
                <a id="historyPriceBtn" class="btn btn-outline btn-success btn-rounded" data-toggle='modal'
                   data-target="#historyPriceModal" onclick="showHistoryPrice()"
                   shiro:hasPermission="orderItem:showPrice">
                    <i class="fa fa-rmb"></i> 历史价格
                </a>
            </div>
            <table id="orderItem" data-mobile-responsive="true"></table>
        </div>
    </div>
    <!--上传报告-->
    <div id="uploadModal" style="display: none">
        <div class="modal-body">
            <form id="uploadForm" enctype="multipart/form-data">
                <div style="margin-top:20px">
                    <label><b>上传类型：</b></label>
                    <select id="uploadSelect" name="uploadType">
                    </select>
                    <label style="color: red">*</label>
                </div>
                <div style="margin-top:20px"><label><b>选择文件：</b></label><input type="file" name="reportFile"
                                                                               id="reportFile" style="display:inline">
                    <label style="color: red">*</label></div>
            </form>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" onclick='closeDialog()'>关闭</button>
            <button type="button" class="btn btn-primary" onclick='uploadReport()'>确定</button>
        </div>
    </div>

    <!--下载报告-->
    <div id="downloadModal" style="display: none">
        <div class="modal-body">
            <form id="downloadForm" method="post">
                <div class="checkbox" id="downloadCheckbox">
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" onclick='closeDialog()'>关闭</button>
            <button type="button" class="btn btn-primary" onclick='downloadReport()'>确定</button>
        </div>
    </div>
</div>

<!-- 模态框（Modal） -->
<div id="myMailModal" style="display: none">
    <div class="modal-body">
        <div class="form-group">
            <label>收件人</label><label style="color: red">(多个收件人以英文字符 ; 分开)</label>
            <textarea id="email" class="form-control" rows="5"></textarea>
        </div>
        <br/>
        <div class="form-group">
            <label>内容</label>
            <textarea id="remark" class="form-control" rows="5"></textarea>
        </div>
        <div class="form-group">
            <label>供应商</label>
            <textarea id="vendorName" class="form-control" rows="5"></textarea>
        </div>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal" onclick="closeDialog()">关闭</button>
        <button type="button" class="btn btn-primary" data-dissmiss="modal" onclick="sendmail()">发送</button>
    </div>
</div><!-- /.modal-dialog -->

<!--供应商回复交期-->
<div id="replyDateModal" style="display: none">
    <div class="modal-body" style="margin-bottom: 70px;padding-top: 50px;">
        <label>回复交期：</label>
        <input id="replyDateInput" style="display: inline;width: 200px;" type="text" class="form-control"
               autocomplete="off">
        <label style="color: red">*</label>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-default" onclick='closeDialog()'>关闭</button>
        <button type="button" class="btn btn-primary" onclick='updateReplyDate()'>确定</button>
    </div>
</div>

<!-- 历史价格 -->
<div class="modal fade" id="historyPriceModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" role="document" style="width:70%">
        <div class="modal-content" style="height:700px">
            <form id="historicalPriceForm" th:action="@{/historicalPrice/nproVendorList}" class="form-inline">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    <h4 class="modal-title">历史价格</h4>
                </div>
                <div class="modal-body" style="height:90%;overflow:auto">
                    <div style="height: 30px;width:100%">
                        <ul>
                            <li class="col-sm-3" style="width: 40%">
                                <label style="width: 100px">物料描述：</label>
                                <input name="materialDesc" type="text" id="materialDesc" class="form-control"
                                       placeholder="物料描述">
                            </li>
                            <li class="col-sm-3" style="width: 20%">
                                <button id="historicalPriceSearchBtn" type="button"
                                        class="btn btn-primary btn-rounded btn-sm"><i class="fa fa-search"></i>&nbsp;搜索
                                </button>
                                <button class="btn btn-warning btn-rounded btn-sm" type="reset"><i
                                        class="fa fa-eraser"></i>&nbsp;重置
                                </button>
                            </li>
                        </ul>
                    </div>
                    <table class="table table-bordered text-nowrap" id="historicalPrice"></table>
                </div>
            </form>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
<!-- 订单的详细模态框（Modal） -->
<div id="myPoNoModal" style="display: none">

    <table class="layui-table" style="width:90%;margin: 10px auto">
        <tr>
            <td>采购凭证号</td>
            <td>供应商</td>
            <td>供应商名称</td>
            <td>物料描述</td>
            <td>采购订单数量</td>
            <td>含税单价</td>
            <td>订单总价值</td>
            <td>单位</td>
            <td>货币码</td>
            <td>税码</td>
            <td>供应商回复交期</td>
        </tr>
        <tr>
            <td id="no"></td>
            <td id="code"></td>
            <td id="name"></td>
            <td id="mDesc"></td>
            <td id="poCountId"></td>
            <td id="price"></td>
            <td id="totalprice"></td>
            <td id="uint"></td>
            <td id="curry"></td>
            <td id="taxCode"></td>
            <td id="date"></td>
        </tr>
    </table>

    <div id="footer" style="margin-left:1090px;margin-top: 20px">
        <button class="btn btn-success" onclick="closeDialog()">关闭</button>
    </div>
</div>

<!--引入公共js-->
<div th:include="common/onload_js :: onloadJS"></div>
<script type="text/javascript" th:src="@{/static/js/plugins/jquery-layout/jquery.layout-latest.js}"></script>
<!-- Page-Level Scripts -->
<script type="text/javascript">
    //面向对象
    var searcherBS = Searcher.createBS('#orderItem',
        [
            {checkbox: true},
            {
                title: "操作", field: '操作',
                formatter: function (value, row, index) {
                    value = '<button   class="btn btn-outline btn-success btn-rounded"    onclick="fun(\'' + index + '\')">查看</button>';
                    return value;
                }
            },
            {title: '采购凭证号', field: 'poNo'},
            {title: '行项目号', field: 'itemNo'},
            {
                title: '订单状态', field: 'itemStatus',
                formatter: function (value, row, index) {
                    var status = '';
                    if (value == '0') {
                        status = '草稿';
                    } else if (value == '-1') {
                        status = '已驳回';
                    } else if (value == '1') {
                        status = '已确认';
                    } else if (value == '2') {
                        status = '分批发货';
                    } else if (value == '3') {
                        status = '发货完毕';
                    } else if (value == '4') {
                        status = '已同步SAP';
                    }
                    return status;
                }
            },
            {title: '采购组', field: 'purchGroup'},
            {title: '供应商', field: 'sapCode'},
            {title: '供应商名称', field: 'vendorName'},
            {title: '物料描述', field: 'materialDesc'},
            {title: '采购订单数量', field: 'poCount'},
            {title: '含税单价', field: 'poPrice'},
            {title: '订单总价值', field: 'totalPrice'},
            {title: '采单位', field: 'poUnit'},
            {title: '货币码', field: 'currencyCode'},
            {title: '税码', field: 'taxCode'},
            {title: '采购申请编号', field: 'prNo'},
            {title: '采购申请项目编号', field: 'prItemNo'},
            {title: '需求者姓名', field: 'requester'},
            {title: '需求日期', field: 'deliveryDate'},
            {title: '供应商回复交期', field: 'replyDate'},
            {title: '物料组', field: 'materialGroup'},
            {title: '待发货的数量', field: 'backOrders'},
            /*{title: '最小起订量', field: 'priceUnit'},*///最小起订数量
            {title: '总账科目', field: 'materialCode'},
            {title: '成本中心', field: 'costCenter'},
            {title: '订单类型', field: 'poType'},
            {title: '工厂', field: 'factory'},
            {title: '公司代码', field: 'companyCode'},
            {title: '采购组织', field: 'purchOrg'},
            {
                title: "免费", field: 'free',
                formatter: function (value, row, index) {
                    if (value == 0) {
                        return "非免费的"
                    } else {
                        return "免费的"
                    }
                }
            },
            /*{title: '采购订单更改日期', field: 'sapUtime'},*/
            {title: '付款条件代码', field: 'payCondition'},
            {
                title: '备注', field: 'remark',
                width: "150px",
                cellStyle: formatTableUnit,
                formatter: paramsMatter
            },
            {title: '创建日期', field: 'creationDate'},
            /*{
                title: "二维码下载", field: '',
                formatter: function (value, row, index) {
                    return '<a class="btn btn-outline btn-success btn-rounded" onclick="downloadQRcode(\'' + row.poItemId + '\');">二维码下载</a>';
                }
            },*/
            {
                title: '出货检测报告', field: 'testFile',
                formatter: function (value, row, index) {
                    if (value) {
                        return "<img src='" + ctxPath + "/img/duicuo/dui.png' width='20px' />";
                    } else {
                        return "<img src='" + ctxPath + "/img/duicuo/cuo.png' width='20px' />";
                    }
                }
            },
            {
                title: '送货单', field: 'deliverFile',
                formatter: function (value, row, index) {
                    if (value) {
                        return "<img src='" + ctxPath + "/img/duicuo/dui.png' width='20px' />";
                    } else {
                        return "<img src='" + ctxPath + "/img/duicuo/cuo.png' width='20px' />";
                    }
                }
            }
        ]
    );

    //鼠标悬浮显示详细信息
    function paramsMatter(value, row, index) {
        if (!value) {
            return value;
        }
        var span = document.createElement('span');
        span.setAttribute('title', value);
        span.innerHTML = value;
        return span.outerHTML;
    }

    //设置确认的权限
    function infoto() {
        Page.ajaxPOST(ctxPath + "/sys/role/findRoleName", null, function (data) {
            var roleName = data.result;
            for (var i in roleName) {
                console.log(roleName[i]);
                if (roleName [i] == "供应商") {
                    $(".poNo").removeAttr('onclick');
                    $("#historytable").css({'display': "none"});
                    $("#factory").css({'display': "none"});
                }
                if (roleName[i] == "采购专员") {
                    $("#factory").css({'display': "none"});
                }
            }

        });
    }

    //鼠标悬浮显示详细信息
    function formatTableUnit(value, row, index) {
        return {
            css: {
                "text-overflow": 'ellipsis',
                "overflow": 'hidden',
                "word-break": "keep-all"
            }
        }
    }

    // 初始化时间插件
    laydate.render({elem: '#replyDateInput'});


    function downloadQRcode(obj) {
        var poItemId = obj;
        window.location.href = ctxPath + "/orderItem/toDwnload?id=" + poItemId;
    }


    /**
     * 查询数据
     */
    function refresh() {
        searcherBS.refresh();
    }

    $(function () {
        initDictDataSel();//初始化所有字典数据
        infoto();
    });

    /**
     * 编辑
     */
    function toEdit() {
        var rowDatas = searcherBS.getSelectedRows("poNo");
        if (rowDatas.length != 1) {
            Dialog.errorMsg("请选择一行进行编辑!");
            return;
        }
        var selectItems = searcherBS.getRawData();
        for (var item in selectItems) {
            if (selectItems[item].itemStatus != '-1' && selectItems[item].itemStatus != '0') {
                Dialog.errorMsg("订单已确认过，不可变更！");
                return;
            }
        }
        var index = Dialog.openUrl("更改订单信息", ctxPath + '/orderHead/toEdit/' + rowDatas,
            {
                area: ['900px', '700px'],
                maxmin: true,
                end: function () {
                }
            });
        layer.full(index);
    }

    /**
     * 确认订单
     */
    function toUpdate() {
        var rowDatas = searcherBS.getRawData();
        if (rowDatas.length < 1) {
            Dialog.errorMsg("请选择一行进行确认");
            return;
        }
        for (var item in rowDatas) {
            if (rowDatas[item].itemStatus == '1') {
                Dialog.errorMsg("订单已处于确认状态！");
                return;
            } else if (rowDatas[item].itemStatus == '2' || rowDatas[item].itemStatus == '3') {
                Dialog.errorMsg("订单已发货，不能确认！");
                return;
            } else if (rowDatas[item].itemStatus == '4') {
                Dialog.errorMsg("订单已同步SAP，不能确认！");
                return;
            }
        }
        //field:"pkId"
        var poItemIds = searcherBS.getSelectedRows("poItemId");
        Page.ajaxPOST(ctxPath + "/orderItem/toupdate", {"ids": poItemIds}, function () {
            Dialog.msg("操作成功", function () {
                searcherBS.refresh();
            });
        });
    }

    /**
     *供应商回复交期
     */
    function addReplyDate() {
        var rowDatas = searcherBS.getRawData();
        if (rowDatas.length < 1) {
            Dialog.errorMsg("请选择一行添加回复交期！");
            return;
        }
        for (var item in rowDatas) {
            if (rowDatas[item].itemStatus == '2') {
                Dialog.errorMsg("订单已发货，不能添加回复交期！");
                return;
            } else if (rowDatas[item].itemStatus == '3') {
                Dialog.errorMsg("订单已发货完毕，不能添加回复交期！");
                return;
            }
        }
        $("#replyDateInput").val('');
        Dialog.open("添加回复交期", $("#replyDateModal"), {area: ['500px', '300px']});
    }

    /**
     *供应商回复交期更新数据
     */
    function updateReplyDate() {
        var poItemIds = searcherBS.getSelectedRows("poItemId");
        var replyDate = $("#replyDateInput").val();
        if (!replyDate) {
            Dialog.errorMsg("请选择回复交期！");
            return;
        }
        layer.load(1, {shade: [0.3, '#393D49']});
        Page.ajaxPOST(ctxPath + "/orderItem/updateReplyDate", {
            "ids": poItemIds,
            "replyDate": replyDate
        }, function () {
            Dialog.msg("操作成功", function () {
                searcherBS.refresh();
            });
            layer.closeAll();
        });
    }

    /**
     * 取消订单
     */
    function toRemove() {
        var rowDatas = searcherBS.getRawData();
        if (rowDatas.length < 1) {
            Dialog.errorMsg("请选择一行进行驳回！");
            return;
        }
        for (var item in rowDatas) {
            if (rowDatas[item].itemStatus == '2' || rowDatas[item].itemStatus == '3' || rowDatas[item].itemStatus == '4') {
                Dialog.errorMsg("订单已发货或同步SAP后不可驳回！");
                return;
            } else if (rowDatas[item].itemStatus == '-1') {
                Dialog.errorMsg("订单已处于驳回状态！");
                return;
            }
        }
        //field:"pkId"
        var poItemIds = searcherBS.getSelectedRows("poItemId");
        Page.ajaxPOST(ctxPath + "/orderItem/toRemove", {"ids": poItemIds}, function () {
            Dialog.msg("操作成功", function () {
                searcherBS.refresh();
            });
        });
    }

    /**
     发货
     */
    function toSend() {
        var rowDatas = searcherBS.getRawData();
        if (rowDatas.length < 1) {
            Dialog.errorMsg("请选择一行进行发货！");
            return;
        }
        for (var item in rowDatas) {
            if (rowDatas[item].itemStatus == '-1' || rowDatas[item].itemStatus == '0') {
                Dialog.errorMsg("订单未确认，不能发货！");
                return;
            } else if (rowDatas[item].itemStatus == '2') {
                Dialog.errorMsg("订单已分批发货！");
                return;
            } else if (rowDatas[item].itemStatus == '3') {
                Dialog.errorMsg("订单已发货完毕！");
                return;
            } else if (rowDatas[item].itemStatus == '1') {
                Dialog.errorMsg("订单未同步SAP，不能发货！");
                return;
            }
            if (!rowDatas[item].replyDate) {
                Dialog.errorMsg("请填写回复交期！");
                return;
            }
        }
        //field:"pkId"
        var poItemIds = searcherBS.getSelectedRows("poItemId");
        layer.load(1, {shade: [0.3, '#393D49']});
        Page.ajaxPOST(ctxPath + "/orderItem/toSend", {"ids": poItemIds}, function () {
            Dialog.msg("操作成功", function () {
                searcherBS.refresh();
            });
            layer.closeAll();
        });
    }

    /**
     编辑对应的行数据
     */
    function editFormatter(value, row, index) {
        onclick = "Download(\' ' + row.poItemId + ' \');";
        return [
            '<input type="text" id="1plan' + row.poItemId + '" class="form-control edit1" data=' + value + ' value=' + value + ' onblur="addTarget(' + row.poItemId + ',1)"/>'
        ].join("");
    }

    /**
     * 分批发货
     */
    function toSendBatch() {
        var rowDatas = searcherBS.getRawData();
        /* var rowDatas = searcherBS.getSelectedRows("poItemId");
         var status = searcherBS.getSelectedRows("itemStatus");*/
        if (rowDatas.length != 1) {
            Dialog.errorMsg("请选择一行进行发货！");
            return;
        }
        if (rowDatas[0].itemStatus == '-1' || rowDatas[0].itemStatus == '0') {
            Dialog.errorMsg("订单未确认，不能发货！");
            return;
        } else if (rowDatas[0].itemStatus == '3') {
            Dialog.errorMsg("订单已发货完毕！");
            return;
        } else if (rowDatas[0].itemStatus == '1') {
            Dialog.errorMsg("订单未同步SAP，不能发货！");
            return;
        }
        if (!rowDatas[0].replyDate) {
            Dialog.errorMsg("请填写回复交期！");
            return;
        }
        var index = Dialog.openUrl("分批发货", ctxPath + '/orderItem/toSendBatch/NPRO/' + rowDatas[0].poItemId + '/' + rowDatas[0].itemStatus,
            {
                area: ['1000px', '700px'],
                maxmin: true,
                end: function () {
                }
            });
    }

    /**
     * 传输SAP
     */
    function toSendSap() {
        var rowData = $("#orderItem").bootstrapTable('getSelections');
        if (rowData.length < 1) {
            Dialog.errorMsg("至少选择一行同步SAP！");
            return;
        }
        var dates = searcherBS.getSelectedRows("replyDate");
        for (let j in dates) {
            if (dates[j] == null || dates[j] == "") {
                Dialog.errorMsg("该订单没有回复交期，请添加回复交期!");
                return false;
            }
        }
        for (let i = 0; i < rowData.length; i++) {
            if (rowData[i].itemStatus != 1) {
                Dialog.errorMsg("非确认状态不能同步SAP!");
                return false;
            }
        }
        var rowDatas = searcherBS.getSelectedRows("poItemId");
        Page.ajaxPOST(ctxPath + "/orderItem/toSendSap", {"ids": rowDatas}, function () {
            Dialog.msg("同步成功!", function () {
                searcherBS.refresh();
            });
        }, {"loadingMsg": "正在往服务器提交数据……"});
    }


    /**
     *上传报告
     */
    function showUploadDialog() {
        var rowData = searcherBS.getRawData();
        if (rowData.length != 1) {
            Dialog.errorMsg("请选择一行进行上传！");
            return;
        }
        //上传报告窗口
        Dialog.open('文件上传', $("#uploadModal"), {area: ['500px', '300px']});

        var node = "<option value=''>出货检测报告</option>";
        $("#uploadSelect").html(node);
    }

    //取消
    function closeDialog() {
        layer.closeAll();
    }

    function uploadReport() {
        var reportFile = $("#reportFile").val();
        if (!reportFile) {
            Dialog.errorMsg("请上传文件！");
            return;
        }
        var rowData = searcherBS.getRawData()[0];
        var formData = new FormData($('#uploadForm')[0]);
        formData.append("poItemId", rowData.poItemId);
        layer.load(1, {shade: [0.3, '#393D49']});
        $.ajax({
            url: ctxPath + "/orderItem/uploadTestFile",
            type: 'POST',
            data: formData, // 上传formdata封装的数据包
            dataType: 'JSON',
            cache: false, // 不缓存
            processData: false, // jQuery不要去处理发送的数据
            contentType: false, // jQuery不要去设置Content-Type请求头
            success: function (data) {
                layer.closeAll();
                if (data.result) {
                    Dialog.msg("操作成功!", function () {
                    });
                } else {
                    Dialog.msg("操作失败，请重新上传!", function () {
                    });
                }
                searcherBS.refresh();
                //清除表单内容
                $("#reportFile").val("");
                $("#remark").val("");
            }
        });
    }

    /**
     *下载报告
     */
    function showdownloadDialog() {
        var rowData = searcherBS.getRawData();
        if (rowData.length != 1) {
            Dialog.errorMsg("请选择一行进行下载！");
            return;
        }
        rowData = rowData[0];
        var poItemId = rowData.poItemId;
        if (!rowData.testFile && !rowData.deliverFile) {
            Dialog.errorMsg("没有文件上传！");
            return;
        }
        Page.ajaxPOST(ctxPath + "/orderItem/findDownloadDeliverOrTest", {"id": poItemId}, function (res) {
            var index;
            var node = '';
            for (var i in res.result) {
                index = res.result[i];
                node += "<div style='margin:20px;font-size:1.3em'><label><input type='radio' style='margin-top: 6px;' name='id' value='" + index.pkId + "'>" + index.fileName + "</label></div>";
            }
            $("#downloadCheckbox").html(node);
            //下载报告窗口
            Dialog.open("下载文件", $("#downloadModal"), {area: ['500px', '500px']});
        });
    }

    function downloadReport() {
        $("#downloadForm").attr("action", ctxPath + "/orderItem/downloadDeliverOrTest");

        var checkReports = $("input[name='id']:checked");
        var len = checkReports.length;
        if (len == 0) {
            Dialog.errorMsg("请选择要下载的文件！");
            return;
        }
        $("#downloadForm").submit();
        layer.closeAll();
    }

    //显示发送邮件弹出框
    function showMailDialog() {
        var rowData = searcherBS.getRawData();
        if (rowData.length == 0) {
            Dialog.errorMsg("至少选择一项发送邮件！");
            return;
        }
        var email = '';
        var vendorNames = '';
        for (var index in rowData) {
            if (rowData[index].email != null && rowData[index].email != '') {
                email += rowData[index].email + ';';
            }
            vendorNames += rowData[index].vendorName + ';';
        }
        email = email.substr(0, email.length - 1);
        vendorNames = vendorNames.substr(0, vendorNames.length - 1);
        $('#remark').val('');
        $('#vendorName').val(vendorNames);
        $('#email').val(email);
        Dialog.open("发送邮件", $("#myMailModal"), {area: ['800px', '650px']});
    }

    //发送邮件
    function sendmail() {
        //验证信息
        var reg = /^([a-zA-Z0-9._-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
        var email = $("#email").val();
        if (email == null || email.trim() == "") {
            Dialog.errorMsg("邮箱不能为空！");
            return;
        }
        email = $("#email").val().replace(/[\s]/g, "").split(';');
        for (index in email) {
            if (email[index] == "" || email[index] == null || typeof (email[index]) == undefined) {

                email.splice(index, 1);
            } else if (!reg.test(email[index].trim())) {
                Dialog.errorMsg("邮箱格式不正确！");
                return;
            }
        }
        var remark = $("#remark").val().trim();
        if (remark == null || remark == "" || remark == undefined) {
            Dialog.errorMsg("内容不能为空！");
            return;
        }
        var vendorName = $("#vendorName").val().trim();
        if (vendorName == null || vendorName == "" || vendorName == undefined) {
            Dialog.errorMsg("供应商信息不能为空！");
            return;
        }
        var arremail = JSON.stringify(email);

        var myMap = {};
        myMap["arremail"] = arremail;
        myMap["content"] = remark + "\n请登录网站查看：http://" + location.host + "/hssrm/sys/index";
        myMap["vendorName"] = vendorName;
        layer.load(1, {shade: [0.3, '#393D49']});
        $.ajax({
            type: "POST",
            url: ctxPath + "/parityEmail/offerSendMail",
            data: JSON.stringify(myMap),//必须
            contentType: "application/json;charsetset=UTF-8",//必须
            cache: true,
            error: function (data) {
                Dialog.msg("发送失败，请重试！");
                closeDialog();
                layer.closeAll();
            },
            success: function (data) {
                if (data.result == "ok") {
                    Dialog.msg("发送成功！");
                    closeDialog();
                }
                layer.closeAll();
            }
        });
    }

    //删除订单
    function toDelete() {
        var rowData = searcherBS.getRawData();
        if (rowData.length == 0) {
            Dialog.errorMsg("请选择要删除的定单！");
            return;
        }
        var itemIds = [];
        for (var i in rowData) {
            if (rowData[i].itemStatus != 0 && rowData[i].itemStatus != -1) {
                Dialog.errorMsg("非草稿状态定单不可删除！");
                return;
            }
            itemIds.push(rowData[i].poItemId);
        }
        layer.load(1, {shade: [0.3, '#393D49']});
        $.ajax({
            type: "get",
            url: ctxPath + "/orderItem/deleteOrders?type=NPRO&itemIds=" + itemIds,
            //data: JSON.stringify(itemIds),//必须
            contentType: "application/json;charsetset=UTF-8",//必须
            cache: true,
            error: function (data) {
                Dialog.msg("删除失败，请重试！");
                layer.closeAll();
            },
            success: function (data) {
                layer.closeAll();
                if (data.code == 500) {
                    Dialog.errorMsg(data.msg, null, {time: 3000});
                } else {
                    Dialog.msg(data.msg);
                }
                searcherBS.refresh();
            }
        });
    }

    //查看历史价格
    var historyPriceTable = '';

    function showHistoryPrice() {
        if (!historyPriceTable) {
            historyPriceTable = Searcher.createBS('#historicalPrice',
                [
                    {title: "供应商编码", field: "vendorCode"},
                    {title: "供应商名称", field: "vendorName"},
                    {title: "物料描述", field: "materialDesc"},
                    {title: "含税单价", field: "price"},
                    {title: "币种", field: "currency"},
                    {title: "税码", field: "taxCode"}
                ], {pageList: [10], pageSize: 10, showColumns: false, showRefresh: false}
            );
        }
    }

    /**
     * 生成送货单
     */
    function createDeliverOrder() {
        var rowDatas = searcherBS.getRawData();
        if (rowDatas.length <= 0) {
            Dialog.errorMsg("至少选择一行！");
            return false;
        }
        let vendorCode = rowDatas[0].sapCode;
        for (var item in rowDatas) {
            if (rowDatas[item].itemStatus != '3' && rowDatas[item].itemStatus != '2') {
                Dialog.errorMsg("订单未发货！");
                return false;
            }
            if (rowDatas[item].sapCode != vendorCode) {
                Dialog.errorMsg("请选择相同供应商生成送货单！");
                return false;
            }
        }
        var poItemIds = searcherBS.getSelectedRows("poItemId");
        Page.ajaxPOST(ctxPath + "/orderItem/deliverOrder", {"ids": poItemIds}, function (data) {
            if (data.code == 500) {
                Dialog.errorMsg(data.smg, null, {time: 3000});
                return false;
            }
            Dialog.msg("送货单已生成!");
            window.location.href = ctxPath + "/orderItem/downloadDeliverOrTest?id=" + data.result;
        }, {"loadingMsg": "正在往服务器提交数据……"});
    }

    function free() {
        var rowDatas = searcherBS.getRawData();
        if (rowDatas.length < 1) {
            Dialog.errorMsg("至少选择一行！");
            return false;
        }
        var poItemId = searcherBS.getSelectedRows("poItemId");
        Page.ajaxPOST(ctxPath + "/orderItem/setFree", {"poItemId": poItemId}, function (data) {
            if (data.code == 500) {
                Dialog.errorMsg(data.smg, null, {time: 3000});
                return false;
            }
            Dialog.msg("修改成功!");
            searcherBS.refresh();
        }, {"loadingMsg": "正在往服务器提交数据……"});
    }

    /**
     * 确认订单
     */
    function toUpdate() {
        var rowDatas = searcherBS.getRawData();
        if (rowDatas.length < 1) {
            Dialog.errorMsg("请选择一行进行确认");
            return;
        }
        for (var item in rowDatas) {
            if (rowDatas[item].itemStatus == '1') {
                Dialog.errorMsg("订单已处于确认状态！");
                return;
            } else if (rowDatas[item].itemStatus == '2' || rowDatas[item].itemStatus == '3') {
                Dialog.errorMsg("订单已发货，不能确认！");
                return;
            } else if (rowDatas[item].itemStatus == '4') {
                Dialog.errorMsg("订单已同步SAP，不能确认！");
                return;
            }
        }
        //field:"pkId"
        var poItemIds = searcherBS.getSelectedRows("poItemId");
        Page.ajaxPOST(ctxPath + "/orderItem/toupdate", {"ids": poItemIds}, function () {
            Dialog.msg("操作成功", function () {
                searcherBS.refresh();
            });
        });
    }


    /**
     * 查看订单详情
     */
    function fun(index) {
        var rowData = $("#orderItem").bootstrapTable("getData")[index];
        $("#code").text(rowData.sapCode);
        $("#no").text(rowData.poNo);
        $("#name").text(rowData.vendorName);
        $("#price").text(rowData.poPrice);
        $("#date").text(rowData.replyDate);
        $("#mDesc").text(rowData.materialDesc);
        $("#poCountId").text(rowData.poCount);
        $("#totalprice").text(rowData.totalPrice);
        $("#curry").text(rowData.currencyCode);
        $("#taxCode").text(rowData.taxCode);
        $("#uint").text(rowData.poUnit);
        Dialog.open("详情", $("#myPoNoModal"), {area: ['1200px', '320px']});
        $("#materialhistoryDiv").css("display", "none");
    }
</script>
</body>
</html>